package com.pen.interfece.interceptor;

import com.pen.interfece.Context.BaseContext;
import com.pen.interfece.util.JwtUtil;
import com.pen.interfece.util.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;
@Component
@Slf4j
public class UserLoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("Authorization");
        try {
            Map<String,Object> claims = JwtUtil.parseToken(token);
            Long id= Long.parseLong(claims.get("userId").toString());
            log.info(String.valueOf(id));
            BaseContext.setCurrentId(id);
            System.out.println("开始拦截");
            return true;
        }catch (Exception e){
            response.setStatus(401);
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.remove();
    }
}
